import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/Utils/utils.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'Utils/Constants.dart';
import 'Utils/DioUtils.dart';
import 'Api/LoginApi.dart';
import 'dart:developer';

class ServerManage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ServerManageState();
}

class _ServerManageState extends State<ServerManage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _needRegiste = true;
  bool _showRegist = true; //true表示隐藏
  Registe _registe = Registe.public;
  String _warn = '', _settingText = '设 置';

  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
  Map<String, dynamic> _deviceData = <String, dynamic>{};
  PackageInfo _packageInfo = PackageInfo(
    appName: 'Unknown',
    packageName: 'Unknown',
    versionName: 'Unknown',
    versionCode: 'Unknown',
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('设置服务器'),
        centerTitle: true,
      ),
      body: ListView(
        children: <Widget>[
          SizedBox(
            height: 120.0,
            child: Column(
              children: <Widget>[
                Expanded(
                  child: Text(''),
                ),
                Image.asset(
                  'images/logo.png',
                  width: 60.0,
                  height: 60.0,
                ),
                Text('${_packageInfo.appName}'),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.all(20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                TextField(
                  controller: _outController,
                  autofocus: true,
                  decoration: InputDecoration(
                    border: UnderlineInputBorder(),
                    filled: true,
                    fillColor: Color(0xFAFAFA),
                    labelText: '外网地址',
                    hintText: '请输入如50.222.30.22:8099',
                    suffixIcon: GestureDetector(
                      onTap: () {
                        setState(() {
                          _outController.clear();
                        });
                      },
                      child: Icon(Icons.highlight_off),
                    ),
                  ),
//                  keyboardType: TextInputType.number,
                  maxLength: 19,
//                          focusNode: unFN,
                  inputFormatters: <TextInputFormatter>[
                    ///输入限制字符,确认验证格式
                    WhitelistingTextInputFormatter(RegExp(r'[0-9.:]')),
                  ],
                ),
                TextField(
                  controller: _inController,
                  autofocus: true,
                  decoration: InputDecoration(
                    border: UnderlineInputBorder(),
                    filled: true,
                    fillColor: Color(0xFAFAFA),
                    labelText: '内网地址',
                    hintText: '请输入如192.168.1.633:1010',
                    suffixIcon: GestureDetector(
                      onTap: () {
                        setState(() {
                          _inController.clear();
                        });
                      },
                      child: Icon(Icons.highlight_off),
                    ),
                  ),
//                  keyboardType: TextInputType.number,
                  maxLength: 19,
//                          focusNode: unFN,
                  inputFormatters: <TextInputFormatter>[
                    ///输入限制字符,确认验证格式
                    WhitelistingTextInputFormatter(RegExp(r'[0-9.:]')),
                  ],
                ),
                Offstage(
                  child: _showRegiste(),
                  offstage: _showRegist,
                ),
                SizedBox(height: 25.0),
                Text(
                  '终端序列号 : ${_deviceData['deviceId']}',
                  textAlign: TextAlign.left,
                ),
                SizedBox(height: 15.0),
                RaisedButton(
                  color: Colors.blue[400],
                  child: Row(
                    children: <Widget>[
                      Expanded(child: Text('')),
                      Padding(
                        padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                        child: Text(
                          _settingText,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.0,
                          ),
                        ),
                      ),
                      Expanded(child: Text('')),
                    ],
                  ),
                  onPressed: () async {
                    bool _changed = await _ipChanged();
                    if (_changed) {
                      _settingText = '设 置';
                      _connectIP(false);
                    } else
                      _validateRegist();
                  },
                ),
                SizedBox(
                  height: 10.0,
                ),
                InkWell(
                  child: Text(
                    '检测网络',
                    style: TextStyle(
                      fontSize: 15.0,
                      color: Colors.blue,
                    ),
                  ),
                  onTap: () {
                    _connectIP(true);
//                                showInSnackBar('无可以切换的网络');
                  },
                ),
                Text(
                  _warn,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  final TextEditingController _inController = TextEditingController();
  final TextEditingController _outController = TextEditingController();
  final TextEditingController _userController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _initInfo();
    _initUrl();
  }

  Future<Null> _initInfo() async {
    final PackageInfo info = await PackageInfo.fromPlatform();
    SharedPreferences _prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> deviceData;

    try {
      if (Platform.isAndroid) {
        deviceData = _readAndroidBuildData(await deviceInfoPlugin.androidInfo);
      } else if (Platform.isIOS) {
        deviceData = <String, dynamic>{'Error:': 'Don\'t write IOS code.'};
      }
      _prefs.setString(Constants.clientId, deviceData['deviceId']);
      _prefs.setString(Constants.clientName, deviceData['device']);
    } catch (e) {
      print(e);
      deviceData = <String, dynamic>{
        'Error:': 'Failed to get platform version.'
      };
    }
    if (!mounted) return;
    setState(
      () {
        _packageInfo = info;
        _deviceData = deviceData;
      },
    );
  }

  Future<Null> _initUrl() async {
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    _outController.text = (_prefs.getString(Constants.outUrl) ?? '');
    _inController.text = (_prefs.getString(Constants.inUrl) ?? '');
  }

  ///修改存储url

  Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
    return <String, dynamic>{
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      'version.release': build.version.release,
      'version.previewSdkInt': build.version.previewSdkInt,
      'version.incremental': build.version.incremental,
      'version.codename': build.version.codename,
      'version.baseOS': build.version.baseOS,
      'board': build.board,
      'bootloader': build.bootloader,
      'brand': build.brand,
      'device': build.device,
      'deviceId': build.deviceId,
      'display': build.display,
      'fingerprint': build.fingerprint,
      'hardware': build.hardware,
      'host': build.host,
      'id': build.id,
      'manufacturer': build.manufacturer,
      'model': build.model,
      'product': build.product,
      'serial': build.serial,
      'supported32BitAbis': build.supported32BitAbis,
      'supported64BitAbis': build.supported64BitAbis,
      'supportedAbis': build.supportedAbis,
      'tags': build.tags,
      'type': build.type,
      'isPhysicalDevice': build.isPhysicalDevice,
    };
  }

  _showRegiste() {
    if (!_needRegiste) {
      return Text('');
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextField(
            controller: _userController,
            autofocus: true,
            decoration: InputDecoration(
              border: UnderlineInputBorder(),
              filled: true,
              fillColor: Color(0xFAFAFA),
              labelText: '用户名',
              enabled: _registe == Registe.private,
              hintText: '请输入绑定的用户名',
              suffixIcon: GestureDetector(
                onTap: () {
                  setState(() {
                    _userController.clear();
                  });
                },
                child: Icon(Icons.highlight_off),
              ),
            ),
          ),
          SizedBox(
            height: 10.0,
          ),
          Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Radio(
                    value: Registe.private,
                    groupValue: _registe,
                    onChanged: (Registe value) {
                      setState(() {
                        _registe = value;
                      });
                    },
                  ),
                  Text(
                    '私用',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  Radio(
                    value: Registe.public,
                    groupValue: _registe,
                    onChanged: (Registe value) {
                      setState(() {
                        _registe = value;
                      });
                    },
                  ),
                  Text(
                    '公用',
                    style: TextStyle(fontSize: 16.0),
                  ),
                ],
              ),
            ],
          )
        ],
      );
    }
  }

  _connectIP(bool isTest) async {
    ///isTest检测网络时,不更新界面
//    if (!isTest) {
//      _settingText == '设 置';
//    }
    if (_outController.text == '' && _inController.text == '') {
      showInSnackBar("请输入IP地址");
      setState(() {
        _warn = '请输入IP地址';
        if (!isTest) _showRegist = true;
      });
      return;
    } else if (_outController.text != '' && !_validateIP(_outController.text)) {
      showInSnackBar("外网IP格式错误");
      setState(() {
        _warn = '外网IP格式错误';
        if (!isTest) _showRegist = true;
      });
      return;
    } else if (_inController.text != '' && !_validateIP(_inController.text)) {
      showInSnackBar("内网IP格式错误");
      setState(() {
        _warn = '内网IP格式错误';
        if (!isTest) _showRegist = true;
      });
      return;
    }

    bool _outConnected = false, _inConnected = false;
    if (_outController.text != '') {
      Response response = await DioUtils().instance().post(
          'http://' + _outController.text + '/job.aspx',
          data: verifyIP('999'));
      Map<String, dynamic> resp = json.decode(response.data);
      print(resp);
      if (resp['Status'] == '0') {
        _outConnected = true;
      }
    }

    if (_inController.text != '') {
      Response response = await DioUtils().instance().post(
          'http://' + _inController.text + '/job.aspx',
          data: verifyIP('999'));
      Map<String, dynamic> resp = json.decode(response.data);
      print(resp);
      if (resp['Status'] == '0') {
        _inConnected = true;
      }
    }

    if (_outConnected && _inConnected) {
      showInSnackBar("外网内网均可使用");
      setState(() {
        _warn = '外网内网均可使用';
        if (!isTest) _showRegist = false;
      });
    } else if (_outConnected) {
      showInSnackBar("外网可用");
      setState(() {
        _warn = '外网可用';
        if (!isTest) _showRegist = false;
      });
    } else if (_inConnected) {
      showInSnackBar("内网可用");
      setState(() {
        _warn = '内网可用';
        if (!isTest) _showRegist = false;
      });
    } else {
      showInSnackBar("外网内网均不可用");
      setState(() {
        _warn = '外网内网均不可用';
        if (!isTest) _showRegist = true;
      });
    }

    ///检测网络结束
    if (isTest) return;

    if (_inConnected || _outConnected) {
      SharedPreferences _prefs = await SharedPreferences.getInstance();
      if (_inConnected && _outConnected) {
        _prefs.setString(Constants.inUrl, _inController.text);
        _prefs.setString(Constants.url, _inController.text);
        _prefs.setString(Constants.outUrl, _outController.text);
      } else if (_outConnected) {
        _prefs.setString(Constants.inUrl, '');
        _prefs.setString(Constants.url, _outController.text);
        _prefs.setString(Constants.outUrl, _outController.text);
      } else if (_inConnected) {
        _prefs.setString(Constants.inUrl, _inController.text);
        _prefs.setString(Constants.url, _inController.text);
        _prefs.setString(Constants.outUrl, '');
      }
    }

    await _validateRegist();
  }

  bool _validateIP(String text) {
    if (ipExp().hasMatch(text)) {
      return true;
    }
    return false;
  }

  void showInSnackBar(String value) {
    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(value)));
  }

  Future _validateRegist() async {
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    Response response = await DioUtils().instance().post(
        'http://' + _prefs.getString(Constants.url) + '/job.aspx',
        data: await verifyRegister());
    Map<String, dynamic> resp = json.decode(response.data);
    print(resp);
    if (resp['Status'] == '0') {
      ///已注册
//      showInSnackBar('设备已注册,输入账号密码登录');
      Navigator.pop(context);
    } else {
      ///未注册
      setState(() {
        _settingText = '注 册';
      });
//      showInSnackBar(resp['Message']);
    }
  }

  Future _registMobile() async {
    if (_registe == Registe.private && _userController.text == '') {
      showInSnackBar("请输入绑定用户名");
    }
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    Response response = await DioUtils().instance().post(
        'http://' + _prefs.get(Constants.url) + '/job.aspx',
        data: await registMobile(_registe == Registe.private ? '1' : '0',
            _registe == Registe.private ? _inController.text : ''));
    Map<String, dynamic> resp = json.decode(response.data);
    print(resp);
    if (resp['Status'] == '0') {
      ///注册成功
      showInSnackBar('注册成功,请等待管理员审核');
      setState(() {
        _warn = '注册成功,请等待管理员审核';
      });
    } else {
      ///注册失败
      showInSnackBar(resp['Message']);
    }
  }

  Future _ipChanged() async {
    SharedPreferences _prefs = await SharedPreferences.getInstance();
//    if (_inController.text == '' && _outController.text == '') {
//      return true;
//    }
    if (_prefs.getString(Constants.inUrl) != _inController.text ||
        _prefs.getString(Constants.outUrl) != _outController.text) {
      return true;
    }
    return false;
  }
}
